package dao

import (
	"Todolist/config"
	"context"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"strings"
	"time"
)

var _db *gorm.DB

func MySQLInit() {
	mConfig := config.Config.MySql["default"]
	conn := strings.Join([]string{mConfig.UserName, ":", mConfig.Password,
		"@tcp(", mConfig.DbHost, ":", mConfig.DbPort, ")/", mConfig.DbName, "?charset=utf8&parseTime=true"}, "")
	var ormLogger = logger.Default
	if gin.Mode() == "debug" {
		ormLogger = logger.Default.LogMode(logger.Info)

	}
	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                       conn,  //连接数据库
		DefaultStringSize:         256,   //string类型的默认字段
		DisableDatetimePrecision:  true,  //禁用datetime精度，mysql5.6 不支持
		DontSupportRenameIndex:    true,  //重命名索引的时候，采用删除并重建的方式，mysql 5.7版本之前不支持
		DontSupportRenameColumn:   true,  //mysql 8 之前不支持
		SkipInitializeWithVersion: false, //不根据版本进行自动配置

	}), &gorm.Config{
		Logger: ormLogger, //打印日志
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, //表明不加s  user  users
		},
	})
	if err != nil {
		panic(err)
	}

	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(20)  //设置连接池
	sqlDB.SetMaxOpenConns(100) //最大dakai
	sqlDB.SetConnMaxLifetime(time.Second * 30)
	_db = db
	migration()
}

func NewDBClient(ctx context.Context) *gorm.DB {
	db := _db
	return db.WithContext(ctx)
}
